<template>
  <div class="padding" v-loading.fullscreen.lock="fullscreenLoading">
    <el-card class="margin-bottom">
      <div slot="header" class="clearfix relative">
        <el-row class="flex align-center">
          <el-col :span="1"><span class="title-icon">总计</span></el-col>
          <el-col :span="4"> 运单号：{{ waybillInfo.waybillNo }} </el-col>
          <el-col :span="4">
            重量（KG）： {{ waybillInfo.inStockActualWeight }}
          </el-col>
          <el-col :span="4">
            体积（CBM）： {{ waybillInfo.inStockVolume }}
          </el-col>
          <el-col :span="3">
            件数： {{ waybillInfo.inStockTotalPackages }}
          </el-col>
          <el-col :span="3"> 托盘数： {{ waybillInfo.trayNumber }} </el-col>

          <el-col :span="3">
            查看系统日志：

            <el-popover placement="bottom" trigger="hover">
              <div v-html="waybillInfo.sysRemark"></div>
              <i class="fa fa-envelope" slot="reference"></i>
            </el-popover>
          </el-col>
          <el-col :span="2">
            <el-button type="success" class="el-button--mini" @click="save">
              保存分配
            </el-button>
          </el-col>
        </el-row>
      </div>
      <el-row :gutter="30" type="flex">
        <el-col :span="8">
          <el-row class="row-item">
            <el-col :span="12">
              应付总计：
            </el-col>
            <el-col :span="12">
              {{ payTotalCost }} {{ standardCurrency }}
            </el-col>
          </el-row>
          <el-row class="row-item">
            <el-col :span="12">
              利润：
            </el-col>
            <el-col :span="12">
              {{ 0 - payTotalCost }} {{ standardCurrency }}
            </el-col>
          </el-row>
          <el-row class="row-item">
            <el-col :span="12">
              利润率：
            </el-col>
            <el-col :span="12">
              -100%
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8" class="border-lr">
          <el-row class="row-item">
            <el-col :span="12">
              应付公司合计：
            </el-col>
          </el-row>
          <el-row
            class="row-item"
            v-for="(item, k) in groupByCompanyAndCurrency"
            :key="k"
          >
            <el-col :span="12"> {{ k }} </el-col>
            <el-col :span="12">
              <template v-if="item">
                <span v-for="(i, v) in item" :key="i"> {{ v }} {{ i }} </span>
              </template>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <div slot="header" class="clearfix relative">
        <span class="title-icon">应付</span>

        <el-button
          style="margin-right:85px;"
          type="text"
          size="mini"
          class="header-save-btn"
          @click="addPayable"
        >
          新增
        </el-button>
      </div>

      <HotTable
        ref="hotTable"
        :templateName="`Receivable`"
        :templateData.sync="payableData"
        :templateOptUser="optUser"
        :templateOptions="templateOptions"
        :templateType="`payable`"
        :templateDelPayIds.sync="delPayIds"
        class="margin-top text-sm"
      ></HotTable>
    </el-card>
  </div>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import { untransform } from "@/store/yg/common/uri";
import { clone } from "@/utils/clone";
import HotTable from "./components/HotTable";
import { m } from "@/store/yg/common/local";
import { parseTime, getFindKey } from "@/utils";
export default {
  components: {
    HotTable
  },

  data() {
    return {
      waybillInfo: {},
      fullscreenLoading: false,
      templateOptions: {
        //C类
        paycOptions: ["C0", "C1", "C2", "C3"],
        //账单类型
        options: ["起", "目"],
        //币种
        currencyOptions: [],
        //费用名称：
        configPayNameOptions: [],
        //费用类型
        configPayTypeOptions: [],
        //用户信息
        userOptions: [],
        // 应收对应客户
        companyOptions: [],
        // 应付对应服务商
        serviceOptions: [],
        payNameTypeMap: {}
      },
      loadingOver: true,
      //当前用户
      optUser: "",
      //记录应付删除的ID
      delPayIds: [],
      //应付
      payTotalCost: 0,
      //利润率
      profit: "0%",
      //应付信息
      payMap: {},

      standardCurrency: "RMB",
      restaurants: [],
      selectionList: [],
      selectionPayableList: [],
      isChangeReceivable: false,
      isChangePayable: false,
      //服务商解析管理
      parseServicerMap: {},
      rawData: [],
      payableData: [],
      action: "",
      feeData: [],
      fileList: [{ name: "", url: "" }],
      uploadShow: false,
      parseServicerId: "",
      groupByCompanyAndCurrency: {}
    };
  },
  methods: {
    m(k) {
      return m(k);
    },
    async init() {
      this.fullscreenLoading = true;
      const uri = "/api/entry/source?bean=userSource";
      const { data: userOptions } = await axios.post(constant.API_SERVER + uri);
      this.fullscreenLoading = false;
      let userArr = [];
      for (const i in userOptions) {
        userArr.push(userOptions[i]);
      }
      this.templateOptions.userOptions = userOptions;
      const {
        success,
        payTotalCost,
        currencyMap,
        standardCurrency,
        payments,
        serviceCompanyMap,
        configPayNameMap,
        billTypeMap,
        configPayTypeMap,
        waybill,
        groupByCompanyAndCurrency,
        userMap
      } = await ajax("loadPlanReceiveAndPays", {
        id: this.$route.query.pid
      });
      if (success) {
        this.rawData = clone(payments);
        this.groupByCompanyAndCurrency = groupByCompanyAndCurrency;
        this.payTotalCost = payTotalCost;

        // this.receiveTotalCost = receiveTotalCost;
        this.standardCurrency = standardCurrency;
        // 币种
        let currencyOptions = [];
        for (const i in currencyMap) {
          currencyOptions.push(i);
        }
        // 公司名
        let serviceOptions = [];
        for (const i in serviceCompanyMap) {
          if (serviceCompanyMap[i]) {
            serviceOptions.push(serviceCompanyMap[i]);
          }
        }
        // 费用名
        let configPayNameOptions = [];
        for (const i in configPayNameMap) {
          if (configPayNameMap[i]) {
            configPayNameOptions.push(configPayNameMap[i]);
          }
        }

        this.templateOptions.currencyOptions = currencyOptions;
        this.templateOptions.serviceOptions = serviceOptions;
        this.templateOptions.configPayNameOptions = configPayNameOptions;
        this.templateOptions.configPayNameMap = configPayNameMap;
        this.templateOptions.configPayTypeMap = configPayTypeMap;
        this.templateOptions.serviceCompanyMap = serviceCompanyMap;
        this.templateOptions.userMap = userMap;
        this.optUser = this.$store.state.auth.user.name;
        this.waybillInfo = waybill;
        console.log("this.templateOptions :>> ", this.templateOptions);
        let payableData = [];
        for (const i of payments) {
          // i.readOnly = true;
          i.serCusId = serviceCompanyMap[i.serCusId];
          i.costName = configPayNameMap[i.costName];
          i.billType = billTypeMap[i.billType];
          i.inputUser = userOptions[i.inputUser];
          if (!i.costNameType && i.costName) {
            i.costNameType = configPayTypeMap[i.costNameType];
          }
          i.lastOperator = i.lastOperator ? userOptions[i.lastOperator] : "";
          payableData.push(i);
        }
        this.payableData = payableData;
      } else {
        this.$message.error("服务器错误！");
      }
    },

    async save() {
      this.fullscreenLoading = true;
      let arr = [];
      for (const j of this.payableData) {
        const d = this.sortData(j);
        arr.push(d);
      }

      const params = {
        waybillId: this.$route.query.pid,
        payments: arr,
        delPaymentIds: this.delPayIds
      };

      const data = await ajax("saveTofbaLoadPlanReceiveAndPays", params);
      this.fullscreenLoading = false;
      if (data.success) {
        this.$message.success("保存成功！");
        this.init();
      } else {
        this.$message.error(this.m(data.errorTips));
      }
    },
    sortData(data) {
      const j = clone(data);

      if (j.inputUser) {
        j.inputUser = Number(
          getFindKey(j.inputUser, this.templateOptions.userMap)
        );
      }

      if (j.lastOperator) {
        j.lastOperator = Number(
          getFindKey(j.lastOperator, this.templateOptions.userMap)
        );
      }
      if (j.serCusId) {
        j.serCusId = getFindKey(
          j.serCusId,
          this.templateOptions.serviceCompanyMap
        );
      }
      console.log("222 :>> ", j.serCusId);
      if (j.costName) {
        j.costName = getFindKey(
          j.costName,
          this.templateOptions.configPayNameMap
        );
      }

      console.log("j.costName :>> ", j.costName);

      j.billType = j.billType === "起" ? 0 : 1;

      return j;
    },

    addPayable() {
      var payble = {
        id: "",
        serCusId: "",
        costName: "",
        costNameType: "",
        inputUser: this.optUser,
        lastModifier: this.optUser,
        unitPrice: "",
        count: "",
        currency: "",
        totalCost: "",
        remain: "",
        billType: "",
        amoebaSubjectId: "",
        accountDate: parseTime(new Date().toLocaleDateString(), "{y}-{m}-{d}"),
        remark: ""
      };
      this.payableData.push(payble);
    },
    async initUserOptions(bean) {
      const uri = "/api/entry/source?bean=userSource";
      axios.post(constant.API_SERVER + uri).then(
        response => {
          this.userOptions = response.data;
        },
        error => {
          console.info(error);
        }
      );
    }
  },
  created: function() {
    this.action =
      constant.API_SERVER +
      "/api/consume/upload?uri=" +
      untransform(this.$route.params.uri) +
      "&f=imporWaybillPayFeePdf&type=blank&name=sub";
  },
  mounted() {
    this.init();
  }
};
</script>

<style lang="scss" scoped>
.border-lr {
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
}

/deep/ .el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
<style>
.handsontable th {
  background: #fff;
  color: #2c3e50;
  text-align: left;
  font-weight: bold;
}

.el-card__body {
  color: #606266;
}

.handsontable th:first-child,
.handsontable th:nth-child(2),
.handsontable td:first-of-type,
.handsontable tr th,
.handsontable tr td,
.handsontable tr:first-child th,
.handsontable tr:first-child td {
  border-color: #ebeef5;
}
</style>
